package com.gnerv.sylvanas.business.manage.storage;

import com.gnerv.sylvanas.business.manage.model.dto.ApiDTO;
import com.gnerv.sylvanas.business.manage.model.entity.Api;
import com.gnerv.sylvanas.business.manage.repository.mapper.ApiMapper;
import com.gnerv.sylvanas.business.manage.repository.mapper.RoleApiMapper;
import com.gnerv.sylvanas.framework.core.cache.CacheService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * @author Gnerv LiGen
 */
@Slf4j
@Service
@AllArgsConstructor
public class ApiStorageService {

    private final ApiMapper apiMapper;
    private final RoleApiMapper roleApiMapper;
    private final CacheService cacheService;


    public int insert(Api api) {
        return apiMapper.insert(api);
    }


    public int deleteByUkId(String ukId) {
        return apiMapper.deleteByUkId(ukId);
    }


    public int updateByUkId(Api api) {
        return apiMapper.updateByUkId(api);
    }


    public ApiDTO selectByUkId(String ukId) {
        return apiMapper.selectByUkId(ukId);
    }


    public List<ApiDTO> selectListByName(String name, int limitStart, int limitSize) {
        return apiMapper.selectListByName(name, limitStart, limitSize);
    }


    public Set<String> selectListAuthorityByAccountUkId(String accountUkId) {
        return apiMapper.selectListAuthorityByAccountUkId(accountUkId);
    }


    public List<ApiDTO> selectListByRoleUkId(String roleUkId) {
        return apiMapper.selectListByRoleUkId(roleUkId);
    }


    public String selectAuthorityByUriAndType(String uri, String type) {
        Object object = cacheService.get(type + "_" + uri);
        if (object != null) {
            return String.valueOf(object);
        }
        String authority = apiMapper.selectAuthorityByUriAndType(uri, type);
        if (authority != null) {
            cacheService.set(type + "_" + uri, authority);
        }
        return authority;
    }


    public int selectCountByName(String name) {
        return apiMapper.selectCountByName(name);
    }


    public int selectCountByUriAndType(String uri, String type) {
        return apiMapper.selectCountByUriAndType(uri, type);
    }


    public int bindRole(String apiUkId, Set<String> roleUkIdList, String creator) {
        return roleApiMapper.insertApiRole(apiUkId, roleUkIdList, creator);
    }


    public int unbindRole(String apiUkId) {
        return roleApiMapper.deleteByApiUkId(apiUkId);
    }


    public List<ApiDTO> selectListByGroupUkId(String groupUkId, int limitStart, int limitSize) {
        return apiMapper.selectListByGroupUkId(groupUkId, limitStart, limitSize);
    }


    public List<ApiDTO> selectListByAccountUkId(String accountUkId) {
        return apiMapper.selectListByAccountUkId(accountUkId);
    }

}
